package com.hisense.ovcloud.apicontrol.tool;

import com.hisense.hitv.ByteUtils;
import com.hisense.ovcloud.apicontrol.errors.CommonConstants;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.security.Security;

@Slf4j
@NoArgsConstructor
public class ControllerUtil {

    static {
        log.info("add BouncyCastleProvider");
        Security.addProvider(new BouncyCastleProvider());
    }

    // 从配置文件指定的RSA密钥文件中获取密钥字节流
    public static final byte[] getRsaPrivateKeyBytes(String rsaPrivateKeyFile) {
        File privateKeyFile = new File(rsaPrivateKeyFile);
        if (privateKeyFile.exists()) {
            try {
                byte[] privateKeyBytes = ByteUtils.readBytesFromFile(privateKeyFile);
                return privateKeyBytes;
            } catch (Exception e) {
                log.error("", e);
                return null;
            }
        } else {
            return null;
        }

    }

    public static boolean verifyRsaSignatureWithSHA256(String contentStr, String salt, String sign, String rsaPrivateKeyBytesFilePath, int srcType) {
        try {
            log.info("content:{},salt:{},sign:{},srcType:{}", contentStr, salt, sign, srcType);
            // 从密钥文件中获取密钥字节流
            byte[] privateKeyBytes = EncryptUtils.getPrivateKey(ControllerUtil.getRsaPrivateKeyBytes(rsaPrivateKeyBytesFilePath)).getEncoded();
            byte[] enBytes = EncryptUtils.rsaDecryptByPrivateKey(ByteUtils.decodeBase64String(sign), privateKeyBytes);
            String decryptContent;
            String sha256Content;
            decryptContent = ByteUtils.encodeBase64String(enBytes);
            if (srcType == CommonConstants.SOURCE_TYPE_WEB) {
                decryptContent = new String(enBytes, StandardCharsets.UTF_8);
            }
            log.info("decryptContent:{}", decryptContent);
            sha256Content = ByteUtils.encodeBase64String(Encrypt2Utils.String2SHA256ByteJava(contentStr, salt));
            if (srcType == CommonConstants.SOURCE_TYPE_WEB) {
                sha256Content = HEX(Encrypt2Utils.String2SHA256ByteJava(contentStr, salt));
            }
            log.info("sha256Content:{}", sha256Content);
            return sha256Content.equals(decryptContent);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public static String HEX(byte[] data) {
        StringBuilder sb = new StringBuilder();
        for (byte b : data) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String contentStr = "accessToken=ta1SQFGCpIE-_ZFaGjzlw2GhgDsT34bewAPFQUAfa5Vz8G_szz2s0AjGs4vZqNT0ThhtwWlWZl3JcbooT4ujZnYo40_91XqeqwgkkyN7AF7XxMrU_SGeymaBaSZBpE9-wirxzGZhvV4ta_yOc_PUV2FwbEQ9JTkoXsE5gjEhC32-_Cu5FJo-EtDnaQJqqGbWDFsfZlvNCFUIx1bTZ8Lqa8xVAwe7DAHB9B8fT1aVOQuQsJsJTgqOnJAcBIhib5SA1o6ci7_yRQMAHl6tYYo6N3dhn-3wjC_XsO_ZxSOVVvBf47NQv6gxB9-qm2sug6YxehUVrNUSxnfZYVXTdfNw_vEvOwcmEPPtkUwD3c0pZF9A3gVGdTJbXBb3hjPdSNFm6LIsqqSd1oM0ZPjnmSUl2CNT4kJhCM3RPW1BOV6GEqTths&appId=5065090793492&appSecret=cW12jvV8DYFLNYS80XNCANGOHskZ1ze_C2NqNHt9UF9fKpJK23bqc6OMr20ExObd&homeId=1537&languageId=1&randStr=593454&sourceId=td00100200008244DCABCA6E4D2BA5948FB8196213DA&timeStamp=1740550367459&timezone=8&version=5.0&wifiId=86500410004000400040000004c742521708";
        String salt = "D9519A4B756946F081B7BB5B5E8D1197";
        String sign = "Hm8uHDANulZMZFuzPiRkTgLuZ4G9HqFa+jk0c7nlAzmJxQ6nTJNkOzRtuTeIaEuCi4gRDUsQF7Vfdn4l23gD/M2w421yWRtS79dBvdAQbWgkkm5nWMLX1SmCnD+Xm2tREHMPzls6ScZtuqIkTowtJbFIvMUfal/f6FjdCpG+45oV5cO1GsLerxSvtBYCjuQT2ZCYve3HCBAEbK7ufjM0ia//rJwxbQ21Kd77maYfbukvH+FP3aU3krmjCkDIXF2nlwiWu/XAl2vja6lyYTBuVtb7HBsyxT0d87rh62Ta+K7XTVIl1UbeZ7LYajKXWtpwr+edkM4zDgmD9pEnd5Uvmg==";
        int srcType = 0;
        ControllerUtil util = new ControllerUtil();
        String path = "D:\\WORKSPACE\\CODE\\JAVA17\\neo-api-control\\api-control\\src\\main\\resources\\sh\\rsa_private_key.key";
        System.out.println(util.verifyRsaSignatureWithSHA256(contentStr, salt, sign, path, srcType));
    }
}
